﻿using Enter.SignalR.Entities;
using Enter.SignalR.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace Enter.SignalR.Pages
{
    public class IndexModel : PageModel
    {
        public static int all_count = 0;
        private readonly ILogger<IndexModel> _logger;
        private readonly IFreeSql _fsql;

        public IndexModel(ILogger<IndexModel> logger, IFreeSql fsql)
        {
            _logger = logger;
            _fsql = fsql;
        }

        public List<SendModel> Messages { get; set; } = new List<SendModel>();

        public long MinId { get; set; } 

        public void OnGet()
        {
            var user = HttpContext.Session.GetString("User");
            if (string.IsNullOrWhiteSpace(user))
            {
                var count = Interlocked.Increment(ref all_count);
                HttpContext.Session.SetString("User", "神秘嘉宾" + count);
            }
            var list = _fsql.Select<HistoryMessage>().OrderByDescending(t => t.Id).Take(10).ToList();
            foreach (var item in list)
            {
                Messages.Add(new SendModel
                {
                    User = item.User,
                    Message = item.Message,
                    Time = item.Time.ToString("HH:mm:ss"),
                    Images = JsonSerializer.Deserialize<string[]>(item.Images)
                });
                MinId = item.Id;
            }
            
        }

        public IActionResult OnGetMore(long id)
        {
            long minId = 0;
            List<SendModel> data = new List<SendModel>();
            var list = _fsql.Select<HistoryMessage>().Where(t=>t.Id < id).OrderByDescending(t => t.Id).Take(10).ToList();
            foreach (var item in list)
            {
                data.Add(new SendModel
                {
                    User = item.User,
                    Message = item.Message,
                    Time = item.Time.ToString("HH:mm:ss"),
                    Images = JsonSerializer.Deserialize<string[]>(item.Images)
                });
                minId = item.Id;
            }
            return new JsonResult(new { ok = true, data = data, minId = minId });
        }

        // https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/file-uploads?view=aspnetcore-5.0
        [BindProperty]
        public IndexViewModel FileUpload { get; set; }
        public async Task<IActionResult> OnPostUploadAsync()
        {
            var images = new List<string>();
            if (FileUpload.FormFiles != null)
            {
                foreach (var formFile in FileUpload.FormFiles)
                {
                    if (formFile.Length > 0)
                    {
                        var fileInfo = CreateFile(formFile.FileName);

                        using (var stream = System.IO.File.Create(fileInfo.FileInfo.FullName))
                        {
                            await formFile.CopyToAsync(stream);
                        }

                        images.Add(fileInfo.PathName);
                    }
                }
            }
            var model = new HistoryMessage
            {
                Id = 0,
                User = FileUpload.User,
                Message = FileUpload.Message,
                Time = DateTime.Now,
                Images = JsonSerializer.Serialize(images)
            };
            var count = _fsql.Insert<HistoryMessage>(model).ExecuteAffrows();

            var data = new SendModel { 
                User = model.User, 
                Message = model.Message,
                Time = model.Time.ToString("HH:mm:ss"),
                Images = images.ToArray(),
            };
            return new JsonResult(new { ok = true, data = data });
        }

        public static (FileInfo FileInfo, string PathName) CreateFile(string fileName)
        {
            var extension = Path.GetExtension(fileName);
            var newFileName = Guid.NewGuid() + extension;
            var pathName = Path.Combine("upload", newFileName);
            var fileInfo = GetFile(pathName);
            return (fileInfo, pathName);
        }

        public static FileInfo GetFile(string pathName)
        {
            var root = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
            var fileInfo = new FileInfo(Path.Combine(root, pathName));
            if (!fileInfo.Directory.Exists)
            {
                fileInfo.Directory.Create();
            }
            return fileInfo;
        }
    }

    public class IndexViewModel
    {
        [Required]
        public List<IFormFile> FormFiles { get; set; }
        public string User { get; set; }
        public string Message { get; set; }
    }
}
